package com.feibi.study.Adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
import com.feibi.study.R
import java.util.ArrayList

class ChooseAdapter(
    var context: Context,
    var menus: ArrayList<String>,
    var chooseList: ArrayList<String>
) : RecyclerView.Adapter<ChooseAdapter.ViewHolder?>() {
    var choosePosList: ArrayList<Int> = arrayListOf()

    @NonNull
    override fun onCreateViewHolder(@NonNull viewGroup: ViewGroup, i: Int): ViewHolder {
        val view: View = LayoutInflater.from(viewGroup.context)
            .inflate(R.layout.item_menu, viewGroup, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(@NonNull viewHolder: ViewHolder, @SuppressLint("RecyclerView") i: Int) {
        viewHolder.tv_item.text = menus[i]
        viewHolder.itemView.setOnClickListener { view ->
            if (isChoose(menus[i])) {
                chooseList.remove(menus[i])
                choosePosList.remove(i)
            } else {
                chooseList.add(menus[i])
                choosePosList.add(i)
            }
            notifyItemChanged(i)
        }
        viewHolder.iv_icon.visibility = if (isChoose(menus[i])) View.VISIBLE else View.INVISIBLE
    }

    fun isChoose(menu: String): Boolean {
        for (item in chooseList) {
            if (menu == item) {
                return true
            }
        }
        return false
    }

    override fun getItemCount(): Int {
        return menus.size
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var tv_item: TextView = view.findViewById(R.id.tv_item)
        var iv_icon: ImageView = view.findViewById(R.id.iv_icon)
    }

}